package com.hello.system.service.impl;

import java.io.InputStream;
import com.alibaba.nacos.common.utils.IoUtils;
import org.apache.commons.io.FilenameUtils;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.beans.factory.annotation.Value;
import org.springframework.stereotype.Service;
import org.springframework.web.multipart.MultipartFile;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.hello.common.core.utils.file.FileTypeUtils;
import com.hello.system.service.ISysFileService;
import com.hello.system.utils.FileLogUtils;

/**
 * FastDFS 文件存储
 *
 * @author hello
 */
@Service
public class FastDfsSysFileServiceImpl implements ISysFileService
{
    private static final Logger log = LoggerFactory.getLogger(FastDfsSysFileServiceImpl.class);

    /**
     * 域名或本机访问地址
     */
    @Value("${fdfs.domain}")
    public String domain;

    @Autowired
    private FastFileStorageClient storageClient;

    /**
     * FastDfs文件上传接口
     *
     * @param file 上传的文件
     * @return 访问地址
     * @throws Exception
     */
    @Override
    public String uploadFile(MultipartFile file) throws Exception
    {
        // 使用文件日志工具记录开始上传
        FileLogUtils.logFileUploadStart("FastDFS存储", file, "");
                
        try {
            InputStream inputStream = file.getInputStream();
            StorePath storePath = storageClient.uploadFile(inputStream, file.getSize(),
                    FilenameUtils.getExtension(file.getOriginalFilename()), null);
            IoUtils.closeQuietly(inputStream);
            
            log.info("FastDFS文件上传成功，文件路径: {}，组名: {}", storePath.getPath(), storePath.getGroup());
            
            String url = domain + "/" + storePath.getFullPath();
            
            // 使用文件日志工具记录上传成功
            FileLogUtils.logFileUploadSuccess("FastDFS存储", storePath.getFullPath(), url);
            
            return url;
        } catch (Exception e) {
            // 使用文件日志工具记录上传失败
            FileLogUtils.logFileUploadError("FastDFS存储", file.getOriginalFilename(), e.getMessage());
            throw e;
        }
    }
}
